﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Growatt.Component.Cls;
using Growatt.CreateXLXFormWordRootobject;
using Growatt.DuiHelpers;
using Growatt.ShinebusServiceUploadPack.Service.OSS.Model;
using Newtonsoft.Json;
using static Growatt.CreateXLXFormWord.ShinebusUploadRecordFeishuModel;

namespace Growatt.ShinebusServiceUploadPack.Service.FeishuHelper
{
    public class FileUploadUtils
    {

        public FileUploadUtils()
        {
                
        }

        public FileUploadUtils(string baseID, string tablesID, string accessToken)
        {
            this.baseID = baseID;
            this.tablesID = tablesID;
            this.accessToken = accessToken;
        }

        private string baseID = "FpsPbeuX5aJpM8s7kB4c4U5SnJd";
        private string tablesID = "tblh5eNjYZ9vucEj";
        private string accessToken = "t-e13d5ec1954e82e458f3ce04491c54ea8c9abcef";

        #region MyRegion

        public async Task<string> upload_OnlyOneFileAsynchronous(string filePath)
        {
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();
            // 定义请求地址
            string url = "https://open.feishu.cn/open-apis/drive/v1/medias/upload_all";

            // 准备文件和元信息
            string fileName = Path.GetFileName(filePath); // 文件名
            string parentType = "bitable_file"; // 父类类型
            //string parentType = "bitable_image"; // 父类类型
            string parentNode = baseID; // 点位 token
            string extra = baseID; // 附加信息
            int fileSize = (int)new FileInfo(filePath).Length; // 文件大小

            using (var httpClient = new HttpClient())
            {
                // 设置请求头
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // 创建 MultipartFormDataContent（多部分请求内容）
                var content = new MultipartFormDataContent();

                // 添加文件字段
                var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                var fileContent = new StreamContent(fileStream);
                fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                content.Add(fileContent, "file", fileName);

                // 添加其他字段
                // 文件名
                content.Add(new StringContent(fileName), "file_name");
                // 父类类型
                content.Add(new StringContent(parentType), "parent_type");
                // 父节点
                content.Add(new StringContent(parentNode), "parent_node");
                // 文件大小
                content.Add(new StringContent(fileSize.ToString()), "size");
                // 附加信息
                content.Add(new StringContent(extra), "extra");

                // 发送 POST 请求
                try
                {
                    var response = await httpClient.PostAsync(url, content);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine("文件上传成功:");
                        var responseObject = JsonConvert.DeserializeObject<ApiResponse_upload_all>(responseContent);
                        var file_tokenStr = responseObject.data.file_token;

                        return file_tokenStr;
                    }
                    else
                    {
                        Console.WriteLine($"上传失败，状态码：{response.StatusCode}");
                    }

                    Console.WriteLine(responseContent);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"上传过程出错：{ex.Message}");
                    return string.Empty;
                }
                finally
                {
                    fileStream.Dispose();
                }
            }
            return string.Empty;

        }
        public async Task InsertServerOnlyOneFileAsync(FieldsFileUploadRecordShinebusUtils query)
        {
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();

            using (var httpClient = new HttpClient())
            {

                // 设置请求
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.accessToken);

                // 创建实体对象
                var recordBody = new RecordBodyFileShinebusUploadUploadUtils
                {
                    fields = query,
                };
                // 将实体对象序列化为JSON字符串
                string jsonBody = DuiHelperJson.ObjectToJson(recordBody);

                // 创建请求内容
                var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

                // 发送 POST 请求
                var response = await httpClient.PostAsync(
                    $"https://open.feishu.cn/open-apis/bitable/v1/apps/{baseID}/tables/{tablesID}/records?ignore_consistency_check=true&user_id_type=open_id",
                    content
                );

                // 读取响应内容
                var responseContent = await response.Content.ReadAsStringAsync();
                var responseObject = JsonConvert.DeserializeObject<ApiResponseFileUploadUtils>(responseContent);
                // 处理响应内容
                Console.WriteLine(responseContent);
            }
        }
    

        public async Task<int> UpdateServerAsync(RecordFieldsFileUploadShinebusUtilsBody recordBody, string recordid)
        {
            var apiHelper = new FeishuAPIHelper();
            accessToken = await apiHelper.GetTenantAccessToken();
            var jsonBody = JsonConvert.SerializeObject(recordBody);
            var client = new HttpClient();
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Put,
                RequestUri = new Uri($"https://open.feishu.cn/open-apis/bitable/v1/apps/{baseID}/tables/{tablesID}/records/{recordid}"),
                Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
            };
            request.Headers.Add("Authorization", $"Bearer {accessToken}");

            var response = await client.SendAsync(request);
            var responseContent = await response.Content.ReadAsStringAsync();

            // 反序列化为对象
            var updateResponse = JsonConvert.DeserializeObject<UpdateResponse>(responseContent);
            if (updateResponse != null)
            {
                return updateResponse.code;
            }

            return -1;
        }
        #endregion

        #region 实体类

        public class FieldsFileUploadUtils
        {
            public List<AttachmentItemFileUploadUtils> 升级前运行版本 { get; set; }
            public string 设备型号 { get; set; }
            public string 升级后目标版本 { get; set; }
            public string 更新日志 { get; set; }
            public string 上传正式服务器 { get; set; }
            public double 更新日期 { get; set; }
        }


        public ShinebusUploadFileRecordSofttype[] softType { get; set; }
        public ShinebusUploadFileRecord上传文件成功的ID[] 上传文件成功的ID { get; set; }
        public ShinebusUploadFileRecord产品类型[] 产品类型 { get; set; }
        public ShinebusUploadFileRecord审核通过的云端路径[] 审核通过的云端路径 { get; set; }
        public ShinebusUploadFileRecord新的文件夹的名称[] 新的文件夹的名称 { get; set; }
        public ShinebusUploadFileRecord设备型号[] 设备型号 { get; set; }
        public ShinebusUploadFileRecord设备类型[] 设备类型 { get; set; }



        public class FieldsFileUploadRecordShinebusUtils
        {
            public string 新的文件夹的名称 { get; set; }
            public string 上传文件成功的ID { get; set; }
            public string 审核通过的云端路径 { get; set; }
            public string 设备型号 { get; set; }
            public string 设备类型 { get; set; }
            public string 产品类型 { get; set; }
            public string softType { get; set; }
            public string 是否审核 { get; set; }
            public string 具体操作时间 { get; set; }
        }
        public class AttachmentItemFileUploadUtils
        {
            public string file_token { get; set; }
        }

        public class RecordBodyFileUploadUtils
        {
            public FieldsFileUploadUtils fields { get; set; }
        }
        public class RecordBodyFileShinebusUploadUploadUtils
        {
            public FieldsFileUploadRecordShinebusUtils fields { get; set; }
        }
        public class RecordFileUploadUtils
        {
            public FieldsFileUploadUtils fields { get; set; }
            public string id { get; set; }
            public string record_id { get; set; }
        }

        public class DataFileUploadUtils
        {
            public RecordFileUploadUtils record { get; set; }
        }

        public class ApiResponseFileUploadUtils
        {
            public int code { get; set; }
            public DataFileUploadUtils data { get; set; }
            public string msg { get; set; }
        }
        // 使用示例

        #endregion
    }
}
